// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.IO;
using System.Text;
using Antlr4.Runtime;
using Common.Grammar.Antlr;
using Microsoft.Extensions.DependencyInjection;
using static Common.Grammar.Antlr.CommonParser;

namespace SnapObjects.Expressions
{
    internal abstract class ParserBase
    {
        private readonly CacheCollection<string, ExpressionContext> _cache;

        public ParserBase(IServiceProvider provider)
        {
            _cache = new CacheCollection<string, ExpressionContext>(
                provider.GetService<ICacheProvider>(), CacheSourceKind.RAW_STRING, x => x);
        }

        protected ExpressionContext GetContext(string raw)
        {
            return _cache.GetOrSet(raw, () =>
            {
                var stream = CharStreams.fromString(raw);
                var lexer = new CommonLexer(stream, new StringWriter(), new StringWriter());
                var tokens = new CommonTokenStream(lexer);

                var builder = new StringBuilder();
                var output = new StringWriter();

                var errorBuilder = new StringBuilder();
                var errorOutput = new StringWriter(errorBuilder);

                var parser = new CommonParser(tokens, output, errorOutput);
                var context = parser.expression();

                if (errorBuilder.Length != 0)
                {
                    var message = $"{raw}, {errorBuilder.ToString()}";

                    throw new SyntaxErrorException(message);
                }

                return context;
            });
        }
    }
}
